package cn.itsource.user.interceptor;

import cn.itsource.basic.utils.RedisUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class LoginInterceptor implements HandlerInterceptor {
	//请求到达Controller之前执行
	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object arg2) throws Exception {
		//1.从请求对象里面获取请求头
		String header = req.getHeader("U-TOKEN");
		if (header==null){
			//响应数据
			respJson(resp,"noUser");
			return false;
		}else {
			//1.去redis取值
			String userStr = RedisUtils.INSTANCE.get(header);
			if (userStr==null){//redis里面过期
				//响应数据
				respJson(resp,"expireUser");
				return  false;
			}else {
				//刷新redis里面存储的数据
				RedisUtils.INSTANCE.set(header,userStr,60*30);
				return true;//放行
			}
		}
	}

	public void respJson(HttpServletResponse resp,String msg){
		PrintWriter out = null;
		try {
			resp.setContentType("application/json;charset=UTF-8");
			out = resp.getWriter();
			// {"success":false,"message":"noUser"}
			out.write("{\"success\":false,\"message\":\""+msg+"\"}");
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			out.close();
		}
	}

}
